package foodmaterial.security;

import foodmaterial.entity.JsonResult;
import foodmaterial.entity.ResultCode;
import foodmaterial.filter.ValidateCodeException;
import foodmaterial.utils.JsonUtil;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理登录失败
 */
@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException, ServletException {
        JsonResult result = null;
        if (e instanceof AccountExpiredException) {
            result = new JsonResult(false, ResultCode.USER_ACCOUNT_EXPIRED);//账号过期
        } else if (e instanceof BadCredentialsException) {
            result = new JsonResult(false,ResultCode.USER_CREDENTIALS_ERROR);//密码错误
        } else if (e instanceof CredentialsExpiredException) {
            result = new JsonResult(false,ResultCode.USER_CREDENTIALS_EXPIRED);//密码过期
        } else if (e instanceof DisabledException) {
            result = new JsonResult(false,ResultCode.USER_ACCOUNT_DISABLE);//账号不可用
        } else if (e instanceof LockedException) {
            result = new JsonResult(false,ResultCode.USER_ACCOUNT_LOCKED);//账号锁定
        } else if (e instanceof InternalAuthenticationServiceException) {
            result = new JsonResult(false, ResultCode.USER_ACCOUNT_NOT_EXIST);//用户不存在
        } else if (e instanceof ValidateCodeException) {
            result = new JsonResult(false, e.getMessage());//验证码错误
        }else{
            result = new JsonResult(false,ResultCode.COMMON_FAIL);//其他错误
        }
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JsonUtil.objectToJson(result));

    }
}
